﻿using Common.ConfigurationOptions;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;

namespace Web.Extensions
{
    public static partial class ServiceExtensions
    {
        public static IServiceCollection AddId4Authentication(this IServiceCollection services, IConfiguration configuration)
        {
            if (services is null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            var authenticationOption = configuration.GetSection(AuthenticationOption.Position).Get<AuthenticationOption>();
            if (authenticationOption is null)
            {
                throw new ArgumentNullException(nameof(AuthenticationOption.Position));
            }

            services.AddAuthentication(option =>
            {
                option.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
            {
                options.Authority = authenticationOption.Authority;
                options.Audience = authenticationOption.Audience;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience = false,
                    ValidateIssuer = false,
                };
                options.IncludeErrorDetails = true;
                options.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = (context) =>
                    {
                        var result = context;
                        return Task.CompletedTask;
                    }
                };
            });

            return services;
        }
    }
}
